from typing import List
from common.enum.strategy_group_enum import StrategyGroup
from common.enum.strategy_type_enum import StrategyType
from dto.strategy_assessment import RiskAssessment
from dto.strategy_calculate_result import StrategyCalculateResult
from dto.strategy_info import StrategyInfoMetadata
from service.das.stock_assessment_das import RiskAssessmentService
from service.das.stock_assessment_item_das import (
    AntRiskAssessmentItem,
    RiskAssessmentItemService,
)
from service.das.stock_monitor_das import AntMonitorStock, StockDas
from service.das.strategy_management_das import (
    StrategyInfoModel,
    StrategyManagementService,
)
from config.log_config import AntLogger

class StrategyViewQueryService:

    def searchFinalResultByCode(self, stock_code: str) -> StrategyCalculateResult:
        """通过股票编码查询"""
        return self.searchFinalResult(StockDas().get_stocks_byCode(stock_code))

    def searchFinalResult(self, stockInfo: AntMonitorStock) -> StrategyCalculateResult:
        """
        聚合查询，返回 StrategyCalculateResult 对象
        :param stockInfo: 股票信息对象 (AntMonitorStock)
        :return: 聚合的 StrategyCalculateResult
        """
        try:
            riskService = RiskAssessmentService()
            riskItemService = RiskAssessmentItemService()
            stock_code = stockInfo.stock_code

            # 查询 AntRiskAssessmentModel 的股票信息
            stock_record = riskService.get_risk_assessment_by_code(stock_code)

            # 查询 AntRiskAssessmentItem 的风险明细
            risk_items = riskItemService.query_risk_assessment_items_by_code(stock_code)

            # 创建 StrategyCalculateResult 对象
            result = StrategyCalculateResult(
                stock_info=stockInfo,
                latest_price=stockInfo.monitor_current_price,
                total_score=0,
                risk_level=0,
                focus_level=0,
            )

            # 设置主数据的总得分、风险等级和关注等级
            if stock_record:
                result.total_score = stock_record.final_point or 0
                result.risk_level = stock_record.risk_level or 1
                result.focus_level = stockInfo.stock_focus_level or 1

            # 转换风险明细为 RiskAssessment 对象并添加到结果中
            for item in risk_items:
                risk_assessment = RiskAssessment(
                    stock_code=item.stock_code,
                    description=item.description or "",
                    config=StrategyInfoMetadata(
                        strategy_code=item.strategy_code,
                        strategy_name=item.strategy_name,
                        strategy_group=(
                            self.get_strategy_group_from_code(item.strategy_group)
                        ),  # 使用函数转换
                        strategy_type=(
                            self.get_strategy_type_from_code(item.strategy_type)
                        ),  # 使用函数转换
                        analysis_day=item.analysis_day or 0,
                        strategy_level=item.strategy_level or 1,
                    ),
                    node_point=item.node_point or 0,
                )
                result.risk_assessments.append(risk_assessment)

            # 聚合所有风险明细的节点得分，计算总得分
            result.total_score += sum(
                assessment.node_point for assessment in result.risk_assessments
            )

            return result

        except Exception as e:
            AntLogger.info(f"查询时出错: {e}")
            return StrategyCalculateResult()

    def get_strategy_group_from_code(self, code: int) -> StrategyGroup:
        # 根据 code 返回对应的 StrategyGroup 枚举
        for group in StrategyGroup:
            if group.code == code:
                return group
        return StrategyGroup.PRE_PROCESS  # 默认返回一个策略（可以根据需要调整）

    def get_strategy_type_from_code(self, code: str) -> StrategyType:
        # 根据 code 返回对应的 StrategyType 枚举
        for strategy_type in StrategyType:
            if strategy_type.code == code:
                return strategy_type
        return StrategyType.COMPREHENSIVE  # 默认返回一个策略（可以根据需要调整）

    def get_strategy_list(self) -> List[StrategyInfoModel]:
        strategy_management_das = StrategyManagementService()
        return strategy_management_das.get_all_strategies()
